package com.pxmeta.party.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pxmeta.party.entity.PartyUser;
import com.pxmeta.party.entity.PartyUserCollect;
import com.pxmeta.party.mapper.PartyUserCollectMapper;
import com.pxmeta.party.service.IPartyUserCollectService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 语聊派对表 服务实现类
 * </p>
 *
 * @author wcl
 * @since 2022-06-25
 */
@Service
public class PartyUserCollectServiceImpl extends ServiceImpl<PartyUserCollectMapper, PartyUserCollect> implements IPartyUserCollectService {

    @Override
    public void collect(Long userId, String partyId) {
        PartyUserCollect collect = getCollect(userId, partyId);
        boolean isCollect = findIsCollect(userId, partyId);
        if (isCollect){
            //已收藏，取消收藏
            collect.setIsCollect(Boolean.FALSE);
            this.updateById(collect);
        }else {
            //未收藏，进行收藏
            if (collect == null){
                collect = new PartyUserCollect();
                collect.setIsCollect(Boolean.TRUE);
                collect.setPartyId(partyId);
                collect.setUserId(userId);
                this.save(collect);
            }else {
                collect.setIsCollect(Boolean.TRUE);
                this.updateById(collect);
            }
        }
    }

    @Override
    public boolean findIsCollect(Long userId, String partyId) {
        PartyUserCollect collect = this.getCollect(userId, partyId);
        return collect != null && collect.getIsCollect();
    }

    @Override
    public List<String> findCollectPartyIds(Long userId) {
        LambdaQueryWrapper<PartyUserCollect> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PartyUserCollect::getUserId, userId)
                .eq(PartyUserCollect::getIsCollect,Boolean.TRUE);
        return this.list(wrapper).stream().map(PartyUserCollect::getPartyId).collect(Collectors.toList());
    }


    private PartyUserCollect getCollect(Long userId, String partyId){
        LambdaQueryWrapper<PartyUserCollect> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(PartyUserCollect::getPartyId, partyId)
                .eq(PartyUserCollect::getUserId, userId);
        return this.getOne(wrapper);
    }

}
